package com.example.zhinongbao.provider;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class NewsDao {
    private static final String TAG = "NewsDao";
    private final SQLiteDatabase db;

    public NewsDao(Context context) {
        ZhinongbaoDbHelper dbHelper = new ZhinongbaoDbHelper(context);
        this.db = dbHelper.getWritableDatabase();
    }

    /**
     * 插入新闻数据
     * @param title 新闻标题
     * @param content 新闻内容(HTML格式)
     * @param imageUrl 图片URL
     * @param userId 发布用户ID
     * @return 插入的行ID，-1表示失败
     */
    public long insertNews(String title, String content, String imageUrl, int userId) {
        ContentValues values = new ContentValues();
        values.put(ZhinongbaoContract.NewsEntry.COLUMN_TITLE, title);
        values.put(ZhinongbaoContract.NewsEntry.COLUMN_CONTENT, content);
        values.put(ZhinongbaoContract.NewsEntry.COLUMN_IMAGE_URL, imageUrl);
        values.put(ZhinongbaoContract.NewsEntry.COLUMN_USER_ID, userId);
        values.put(ZhinongbaoContract.NewsEntry.COLUMN_IS_PUBLISHED, 1); // 默认发布状态

        try {
            return db.insert(ZhinongbaoContract.NewsEntry.TABLE_NAME, null, values);
        } catch (Exception e) {
            Log.e(TAG, "插入新闻失败", e);
            return -1;
        }
    }

    /**
     * 更新新闻数据
     * @param newsId 新闻ID
     * @param title 新标题
     * @param content 新内容
     * @param imageUrl 新图片URL
     * @return 受影响的行数
     */
    public int updateNews(long newsId, String title, String content, String imageUrl) {
        ContentValues values = new ContentValues();
        values.put(ZhinongbaoContract.NewsEntry.COLUMN_TITLE, title);
        values.put(ZhinongbaoContract.NewsEntry.COLUMN_CONTENT, content);

        if (imageUrl != null) {
            values.put(ZhinongbaoContract.NewsEntry.COLUMN_IMAGE_URL, imageUrl);
        }

        String selection = ZhinongbaoContract.NewsEntry._ID + " = ?";
        String[] selectionArgs = { String.valueOf(newsId) };

        try {
            return db.update(
                    ZhinongbaoContract.NewsEntry.TABLE_NAME,
                    values,
                    selection,
                    selectionArgs
            );
        } catch (Exception e) {
            Log.e(TAG, "更新新闻失败", e);
            return 0;
        }
    }

    /**
     * 删除新闻
     * @param newsId 新闻ID
     * @return 是否删除成功
     */
    public boolean deleteNews(long newsId) {
        String selection = ZhinongbaoContract.NewsEntry._ID + " = ?";
        String[] selectionArgs = { String.valueOf(newsId) };

        try {
            int deletedRows = db.delete(
                    ZhinongbaoContract.NewsEntry.TABLE_NAME,
                    selection,
                    selectionArgs
            );
            return deletedRows > 0;
        } catch (Exception e) {
            Log.e(TAG, "删除新闻失败", e);
            return false;
        }
    }

    /**
     * 获取所有已发布的新闻
     * @return 新闻列表
     */
    public List<NewsItem> getAllPublishedNews() {
        return getNewsWithSelection(
                ZhinongbaoContract.NewsEntry.COLUMN_IS_PUBLISHED + " = 1",
                null,
                ZhinongbaoContract.NewsEntry.COLUMN_CREATED_AT + " DESC"
        );
    }

    /**
     * 获取用户发布的新闻
     * @param userId 用户ID
     * @return 新闻列表
     */
    public List<NewsItem> getNewsByUser(int userId) {
        String selection = ZhinongbaoContract.NewsEntry.COLUMN_USER_ID + " = ?";
        String[] selectionArgs = { String.valueOf(userId) };

        return getNewsWithSelection(
                selection,
                selectionArgs,
                ZhinongbaoContract.NewsEntry.COLUMN_CREATED_AT + " DESC"
        );
    }

    /**
     * 根据ID获取单条新闻
     * @param newsId 新闻ID
     * @return 新闻条目，找不到返回null
     */
    public NewsItem getNewsById(long newsId) {
        String selection = ZhinongbaoContract.NewsEntry._ID + " = ?";
        String[] selectionArgs = { String.valueOf(newsId) };

        List<NewsItem> result = getNewsWithSelection(selection, selectionArgs, null);
        return result.isEmpty() ? null : result.get(0);
    }

    /**
     * 通用的新闻查询方法
     * @param selection WHERE条件
     * @param selectionArgs WHERE参数
     * @param sortOrder 排序方式
     * @return 新闻列表
     */
    private List<NewsItem> getNewsWithSelection(String selection, String[] selectionArgs, String sortOrder) {
        List<NewsItem> newsList = new ArrayList<>();
        Cursor cursor = null;

        try {
            cursor = db.query(
                    ZhinongbaoContract.NewsEntry.TABLE_NAME,
                    null, // 所有列
                    selection,
                    selectionArgs,
                    null,
                    null,
                    sortOrder
            );

            while (cursor.moveToNext()) {
                NewsItem news = cursorToNewsItem(cursor);
                newsList.add(news);
            }
        } catch (Exception e) {
            Log.e(TAG, "查询新闻失败", e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return newsList;
    }

    /**
     * 将Cursor转换为NewsItem对象
     */
    private NewsItem cursorToNewsItem(Cursor cursor) {
        return new NewsItem(
                cursor.getLong(cursor.getColumnIndexOrThrow(ZhinongbaoContract.NewsEntry._ID)),
                cursor.getString(cursor.getColumnIndexOrThrow(ZhinongbaoContract.NewsEntry.COLUMN_TITLE)),
                cursor.getString(cursor.getColumnIndexOrThrow(ZhinongbaoContract.NewsEntry.COLUMN_CONTENT)),
                cursor.getString(cursor.getColumnIndexOrThrow(ZhinongbaoContract.NewsEntry.COLUMN_IMAGE_URL)),
                cursor.getLong(cursor.getColumnIndexOrThrow(ZhinongbaoContract.NewsEntry.COLUMN_USER_ID)),
                cursor.getLong(cursor.getColumnIndexOrThrow(ZhinongbaoContract.NewsEntry.COLUMN_CREATED_AT)),
                cursor.getInt(cursor.getColumnIndexOrThrow(ZhinongbaoContract.NewsEntry.COLUMN_IS_PUBLISHED)) == 1
        );
    }

    /**
     * 新闻数据模型类
     */
    public static class NewsItem {
        public final long id;
        public final String title;
        public final String content;
        public final String imageUrl;
        public final long userId;
        public final long createdAt;
        public final boolean isPublished;

        public NewsItem(long id, String title, String content, String imageUrl,
                        long userId, long createdAt, boolean isPublished) {
            this.id = id;
            this.title = title;
            this.content = content;
            this.imageUrl = imageUrl;
            this.userId = userId;
            this.createdAt = createdAt;
            this.isPublished = isPublished;
        }

        /**
         * 获取简略内容（用于列表显示）
         */
        public String getBriefContent() {
            // 移除HTML标签
            String plainText = content.replaceAll("<[^>]+>", "");
            // 截取前100个字符
            return plainText.length() > 100
                    ? plainText.substring(0, 100) + "..."
                    : plainText;
        }
    }

    /**
     * 关闭数据库连接
     */
    public void close() {
        if (db != null && db.isOpen()) {
            db.close();
        }
    }
}